package me.baicai.weixin.identity.service.impl;

import com.alibaba.fastjson.JSONObject;
import me.baicai.modules.system.service.dto.MenuDTO;
import me.baicai.utils.StringUtils;
import me.baicai.weixin.entity.gcb.Query;
import me.baicai.weixin.entity.gcb.RecycleDevice;
import me.baicai.weixin.identity.repository.*;
import me.baicai.weixin.application.BasicService;
import me.baicai.weixin.application.Result;
import me.baicai.weixin.conf.IdentityKey;
import me.baicai.weixin.entity.config.ShopMenu;
import me.baicai.weixin.entity.gcb.Device;
import me.baicai.weixin.entity.gcb.PageEntity;
import me.baicai.weixin.entity.identity.Agent;
import me.baicai.weixin.entity.identity.Employee;
import me.baicai.weixin.entity.identity.Identity;
import me.baicai.weixin.entity.identity.Shop;
import me.baicai.weixin.identity.service.AgentService;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class AgentServiceImpl extends BasicService implements AgentService
{

    @Autowired
    private AgentRepository agentRepository;

    @Autowired
    private AccountRepository accountRepository;

    @Autowired
    private ShopRepository shopRepository;

    @Autowired
    private DeviceRepository deviceRepository;

    @Autowired
    private ShopMenuRepository shopMenuRepository;

    @Autowired
    private LoginRepository loginRepository;

    @Autowired
    private EmployeeRepository employeeRepository;

    @Autowired
    private MoneyLogRepository moneyLogRepository;

    @Autowired
    private RecycleDeviceRepository recycleDeviceRepository;

    @Value("${gcb.system}")
    private String gm;

    @Autowired
    private OrderRepository orderRepository;

    @Override
    public Result agentIndex(String openid)
    {
        Map map = new HashMap();
        map.put("deviceCount", agentRepository.getDeviceCount(openid));
        map.put("shopCount", agentRepository.getShopCount(openid));
        map.put("todayAmount", agentRepository.getToDayAmount(openid));
        map.put("account", accountRepository.findByOpenid(openid));
        map.put("agent", agentRepository.findByOpenid(openid));
        return this.success(map);
    }

    @Override
    public Result agentChild(String openid, int page, String input)
    {
        Pageable pageable = new PageEntity(page, 10, Sort.Direction.DESC, "id");
        if (!StringUtils.isEmpty(input))
        {
            input = "%" + input + "%";
            return this.success(agentRepository.findLikeAll(openid, input, pageable));
        }
        return this.success(agentRepository.findAllByParent(openid, pageable));
    }

    @Override
    public Result agentShop(String openid, int page, String input)
    {
        Pageable pageable = new PageEntity(page, 10, Sort.Direction.DESC, "id");
        if (!StringUtils.isEmpty(input))
        {
            input = "%" + input + "%";
            return this.success(shopRepository.findAgentShopByInput(openid, input, pageable));
        }
        return this.success(shopRepository.findAgentShop(openid, pageable));
    }

    @Override
    public Result agentDevice(String openid, int page, String input)
    {

        Pageable pageable = new PageEntity(page, 10, Sort.Direction.DESC, "id");
        if (!StringUtils.isEmpty(input))
        {
            input = "%" + input + "%";
            return this.success(deviceRepository.findAgentDeviceByInput(openid, input, pageable));
        }
        return this.success(deviceRepository.findAgentDevice(openid, pageable));
    }

    @Override
    public Result shopInfo(Integer id)
    {
        return this.success(shopRepository.findShopById(id));
    }

    @Override
    public Result submitShopInfo(Integer id, String name, String tel, String address,
                                 Integer commission, Integer refund, String latitude,
                                 String longitude)
    {
        return this.success(
            shopRepository.sumbitShop(name, address, tel, commission, id, refund, latitude,
                longitude));
    }

    @Override
    public Result submitAgentInfo(Integer id, String name, String tel, String address,
                                  Integer commission)
    {
        return this.success(agentRepository.submitAgentInfo(name, address, tel, commission, id));
    }

    @Override
    public Result shopMenu(Integer id)
    {
        return this.success(shopMenuRepository.findAllByShopId(id));
    }

    @Override
    public Result sumbitShopMenu(List<ShopMenu> lsit)
    {

        for (int i = 0; i < lsit.size(); i++)
        {
            switch (lsit.get(i).getGkey())
            {
                case 1:
                    if (lsit.get(i).getTime() > 1)
                        return this.error("1小时的设置错误！ 不能超过1小时");
                    break;
                case 2:
                    if (lsit.get(i).getTime() > 2)
                        return this.error("2小时的时间设置错误！ 不能超过2小时");
                    break;
                case 3:
                    if (lsit.get(i).getTime() > 12)
                        return this.error("12小时的设置错误！ 不能超过12小时");
                    break;
                case 4:
                    if (lsit.get(i).getTime() > 24)
                        return this.error("24小时的设置错误！ 不能超过24小时");
                    break;
            }
        }
        shopMenuRepository.saveAll(lsit);
        shopMenuRepository.flush();
        return this.success();
    }

    @Override
    public Result shopDevice(Integer id, int page, String input)
    {
        Pageable pageable = new PageEntity(page, 10, Sort.Direction.DESC, "id");
        if (!StringUtils.isEmpty(input))
        {
            input = "%" + input + "%";
            return this.success(deviceRepository.findShopDeviceByInput(id, input, pageable));
        }
        return this.success(deviceRepository.findShopDevice(id, pageable));
    }

    @Override
    public Result deleteDevice(String sn)
    {
        Device device = deviceRepository.findBySn(sn);
        if (device.getVersion().intValue() != 3)
        {
            RecycleDevice recycleDevice = new RecycleDevice(device);
            recycleDeviceRepository.saveAndFlush(recycleDevice);
        }
        return this.success(deviceRepository.deleteBySn(sn));
    }

    @Override
    public Result updateDeviceRemark(String sn, String remark)
    {
        return this.success(deviceRepository.updateDeviceRemark(sn, remark));
    }

    @Override
    public Result submitDevice(String sn, String remark, Integer shopid, Integer version)
    {
        // 先判断是否存在
        if (!sn.startsWith("GCB"))
        {
            return this.error("非法的设备号");
        }

        // 先判断是否存在
        if (deviceRepository.existsBySn(sn))
        {
            return this.error("设备已存在");
        }

        Device device = null;
        // 先判断是否存在

        if (version != 3 && recycleDeviceRepository.existsBySn(sn))
        {
            RecycleDevice recycleDevice = recycleDeviceRepository.getRecycleDeviceBySn(sn);
            device = new Device(sn, remark, shopid, version, recycleDevice.getStep());
            recycleDeviceRepository.delete(recycleDevice);
        }
        else
        {
            device = new Device(sn, remark, shopid, version);
        }
        return this.success(deviceRepository.saveAndFlush(device));
    }

    @Override
    public Result submitAgent(String openid, Integer id, String name, String tel, String address,
                              Integer commission)
    {
        Agent agent = agentRepository.findByOpenid(openid);
        if (agent.getLevel() > 2)
            return this.error(412, "代理等级不够，无法添加子代理！");

        Identity identity = loginRepository.getById(id);
        if (null == identity)
            return this.error(412, "不存在这个ID");

        if (agentRepository.existsByOpenid(identity.getOpenid()))
            return this.error(412, "这个用户已经成为了代理");

        Agent temp = new Agent(identity.getOpenid(), name, address, agent.getLevel() + 1, tel,
            commission, agent.getOpenid(), identity.getAccountId(), new Date());

        agentRepository.saveAndFlush(temp);
        identity.setLevel(agent.getLevel() + 1);
        identity.setType(IdentityKey.agent);
        loginRepository.saveAndFlush(identity);
        return this.success();
    }

    @Override
    public Result submitShop(String openid, String shopName, String tel, String address,
                             Integer commission, Integer id, String name, Integer refund,
                             String latitude, String longitude)
    {

        Identity identity = null;
        if (null != id)
        {
            identity = loginRepository.getById(id);
            if (null == identity)
            {
                return this.error(404, "不存在的ID");
            }
            else
            {
                if (!"".equalsIgnoreCase(name))
                {
                    identity.setName(name);
                    if (identity.getType().equalsIgnoreCase(IdentityKey.customer))
                        identity.setType(IdentityKey.shop);
                    else if (identity.getType().equalsIgnoreCase(IdentityKey.agent))
                        identity.setType(IdentityKey.agent);
                    loginRepository.saveAndFlush(identity);
                }
                Shop shop = new Shop(identity.getOpenid(), shopName, address, tel, commission,
                    openid, latitude, longitude);
                shop.setRefund(refund);
                shopRepository.saveAndFlush(shop);
                ShopMenu shopMenu = new ShopMenu();
                shopMenu.setShopId(shop.getId());
                shopMenu.setGkey(1);
                shopMenu.setIsuse(1);
                shopMenu.setPrice(2F);
                shopMenu.setTime(1);
                shopMenuRepository.saveAndFlush(shopMenu);
                shopMenu = new ShopMenu();
                shopMenu.setShopId(shop.getId());
                shopMenu.setGkey(2);
                shopMenu.setIsuse(1);
                shopMenu.setPrice(3F);
                shopMenu.setTime(2);
                shopMenuRepository.saveAndFlush(shopMenu);
                shopMenu = new ShopMenu();
                shopMenu.setShopId(shop.getId());
                shopMenu.setGkey(3);
                shopMenu.setIsuse(1);
                shopMenu.setPrice(4F);
                shopMenu.setTime(12);
                shopMenuRepository.saveAndFlush(shopMenu);
                shopMenu = new ShopMenu();
                shopMenu.setShopId(shop.getId());
                shopMenu.setGkey(4);
                shopMenu.setIsuse(1);
                shopMenu.setPrice(5F);
                shopMenu.setTime(24);
                shopMenuRepository.saveAndFlush(shopMenu);
            }

        }
        else
        {
            Shop shop = new Shop("", shopName, address, tel, commission, openid, latitude,
                longitude);
            shop.setRefund(refund);
            shopRepository.saveAndFlush(shop);
            ShopMenu shopMenu = new ShopMenu();
            shopMenu.setShopId(shop.getId());
            shopMenu.setGkey(1);
            shopMenu.setIsuse(1);
            shopMenu.setPrice(2F);
            shopMenu.setTime(1);
            shopMenuRepository.saveAndFlush(shopMenu);
            shopMenu = new ShopMenu();
            shopMenu.setShopId(shop.getId());
            shopMenu.setGkey(2);
            shopMenu.setIsuse(1);
            shopMenu.setPrice(3F);
            shopMenu.setTime(2);
            shopMenuRepository.saveAndFlush(shopMenu);
            shopMenu = new ShopMenu();
            shopMenu.setShopId(shop.getId());
            shopMenu.setGkey(3);
            shopMenu.setIsuse(1);
            shopMenu.setPrice(4F);
            shopMenu.setTime(12);
            shopMenuRepository.saveAndFlush(shopMenu);
            shopMenu = new ShopMenu();
            shopMenu.setShopId(shop.getId());
            shopMenu.setGkey(4);
            shopMenu.setIsuse(1);
            shopMenu.setPrice(5F);
            shopMenu.setTime(24);
            shopMenuRepository.saveAndFlush(shopMenu);
        }

        return this.success();
    }

    @Override
    public Result verifyShopID(Integer id)
    {
        Identity identity = loginRepository.getIdentityById(id);
        if (null == identity)
            return this.error(404, "不存在这个ID");
        return this.success(identity.getName());
    }

    @Override
    public Result incomeStatistics(String openid, Integer page, String type)
    {
        Pageable pageable = new PageEntity(page, 10, Sort.Direction.DESC, "created");
        Map map = new HashMap();
        if (type.equalsIgnoreCase("self"))
        {
            map.put("orderCount", moneyLogRepository.getOrderCountBySelf(openid));
            map.put("amount", moneyLogRepository.getAmountBySelf(openid));
            map.put("deviceCount", moneyLogRepository.getDeviceCountBySelf(openid));
            map.put("order", moneyLogRepository.getOrderBySelf(openid, page, pageable));
        }
        else
        {
            map.put("orderCount", moneyLogRepository.getOrderCountByOther(openid));
            map.put("amount", moneyLogRepository.getAmountByOther(openid));
            map.put("deviceCount", moneyLogRepository.getDeviceCountByOther(openid));
            map.put("order", moneyLogRepository.getOrderByOther(openid, page, pageable));
        }

        return this.success(map);
    }

    @Override
    public Result agentDeviceInfo(String openid, Integer page, String input)
    {
        Pageable pageable = new PageEntity(page, 10);
        if (StringUtils.isNotBlank(input))
        {
            return this.success(
                agentRepository.agentDemviceInfo(openid, "%" + input + "%", pageable));
        }
        return this.success(agentRepository.agentDeviceInfo(openid, pageable));
    }

    @Override
    public Result getAgentShop(String openid)
    {
        return this.success(shopRepository.findAllByAgentid(openid));
    }

    @Override
    public Result getAgentEmployee(String openid, String type)
    {
        if (null == type || "".equalsIgnoreCase(type))
            this.error("type 参数请输入值");
        if (!type.equalsIgnoreCase(IdentityKey.engineer) &&
            !type.equalsIgnoreCase(IdentityKey.salesman))
            this.error("type 参数输入错误");
        if (type.equalsIgnoreCase(IdentityKey.shop))
            return this.success(shopRepository.getAllByAgentid(openid));
        return this.success(employeeRepository.getAllByAgentIdAndType(openid, type));
    }

    @Override
    public Result submitEmployee(String openid, String name, Integer id, String type,
                                 String telphone,
                                 String remark)
    {
        if (null == name || "".equalsIgnoreCase(name))
            return this.error("员工名称未输入");
        Identity identity = loginRepository.getIdentityById(id);
        if (null == identity)
            return this.error(404, "不存在的ID");
        if (identity.getType().equalsIgnoreCase(IdentityKey.agent) ||
            identity.getType().equalsIgnoreCase(IdentityKey.shop))
            return this.error("目标身份信息不支持此操作");
        if (employeeRepository.existsByOpenid(identity.getOpenid()))
            return this.error("已经是系统中的员工");
        Employee employee = new Employee(openid, name, identity.getOpenid(), remark, telphone,
            type);
        employeeRepository.save(employee);

        if (type.equalsIgnoreCase(IdentityKey.engineer))
        {
            if (identity.getType().equals(IdentityKey.customer))
                identity.setType(IdentityKey.engineer);
            loginRepository.save(identity);
        }
        else
        {
            if (identity.getType().equalsIgnoreCase(IdentityKey.customer))
                identity.setType(IdentityKey.salesman);
            loginRepository.save(identity);
        }

        return this.success();
    }

    @Override
    public Result deleteEmployee(String openid, Integer id, Integer newId, String type)
    {
        if (null == newId)
            return this.error("请输入ID");
        Employee employee = employeeRepository.findById(newId);
        if (null == employee)
            return this.error("不存在的ID");
        if (!employee.getAgentId().equalsIgnoreCase(openid))
            return this.error("不属于你名下的员工");

        Employee oldEmployee = employeeRepository.findById(id);

        Identity identity = loginRepository.findByOpenid(oldEmployee.getOpenid());
        // 修改原有员工的店铺为新员工的店铺
        if (type.equalsIgnoreCase(IdentityKey.engineer))
            shopRepository.updateEngId(identity.getOpenid(), employee.getOpenid());
        else
            shopRepository.updateSalesmanId(identity.getOpenid(), employee.getOpenid());

        // 删除这个员工并修改信息
        employeeRepository.delete(oldEmployee);

        if (identity.getType().equalsIgnoreCase(IdentityKey.engineer) ||
            identity.getType().equalsIgnoreCase(IdentityKey.salesman))
            identity.setType(IdentityKey.customer);
        loginRepository.saveAndFlush(identity);
        return this.success();
    }

    @Override
    public Result updateEmployee(String openid, Integer id, String shop, String type)
    {
        Employee employee = employeeRepository.findById(id);
        if (type.equalsIgnoreCase(IdentityKey.engineer))
        {
            // 删除此员工涉及的所有店铺
            shopRepository.deleteEngineer(employee.getOpenid());
            // 修改店铺列表
            String[] list = shop.split("#");
            for (String str : list)
            {
                if (null == str || "".equalsIgnoreCase(str))
                {
                    continue;
                }
                String comm = str.split("-")[1];
                if (null == comm || "".equalsIgnoreCase(comm))
                    comm = "0";
                shopRepository.updateEngineer(employee.getOpenid(),
                    Integer.valueOf(comm), Integer.valueOf(str.split("-")[0]));

            }
        }
        else
        {
            shopRepository.deleteSalesman(employee.getOpenid());
            // 修改店铺列表
            String[] list = shop.split("#");
            for (String str : list)
            {
                if (null == str || "".equalsIgnoreCase(str))
                {
                    continue;
                }
                shopRepository.updateSalesman(employee.getOpenid(),
                    Integer.valueOf(str.split("-")[1]), Integer.valueOf(str.split("-")[0]));

            }
        }

        return this.success();
    }

    @Override
    public Result getAgentShopList(String openid, String type)
    {
        if (type.equalsIgnoreCase(IdentityKey.engineer))
            return this.success(shopRepository.findAllByAgentidEngineer(openid));
        else
            return this.success(shopRepository.findAllByAgentidSalesman(openid));
    }

    @Override
    public Result getDeviceOrder(String sn, Integer page)
    {
        Pageable pageable = new PageEntity(page, 10, Sort.Direction.DESC, "id");
        return this.success(deviceRepository.getDeviceOrder(sn, pageable));
    }

    @Override
    public Result orderStatistics(String openid, String date)
    {
        return null;
    }

    @Override
    public Result getDate()
    {
        Date now = new Date();
        Date startDate = DateUtils.addDays(now, -30);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return this.success(
            getDays(sdf.format(startDate), sdf.format(DateUtils.addDays(now, -1))));
    }

    public static List<String> getDays(String startTime, String endTime)
    {

        // 返回的日期集合
        List<String> days = new ArrayList<String>();

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try
        {
            Date start = dateFormat.parse(startTime);
            Date end = dateFormat.parse(endTime);

            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start);

            Calendar tempEnd = Calendar.getInstance();
            tempEnd.setTime(end);
            tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)
            while (tempStart.before(tempEnd))
            {
                days.add(dateFormat.format(tempStart.getTime()));
                tempStart.add(Calendar.DAY_OF_YEAR, 1);
            }

        }
        catch (ParseException e)
        {
            e.printStackTrace();
        }

        return days;
    }

    @Override
    public Result usageAnalysisByAgent(String openid, String date, Integer page, String sort,
                                       String type, String input)
    {
        Pageable pageable = null;
        if (sort.equalsIgnoreCase("desc"))
            pageable = new PageEntity(page, 10, Sort.Direction.DESC, "rate");
        else
            pageable = new PageEntity(page, 10, Sort.Direction.ASC, "rate");

        if (type.equalsIgnoreCase("day"))
        {
            if ("".equalsIgnoreCase(input))
                return this.success(agentRepository.usageAnalysisByAgent(openid, date, pageable));
            else
                return this.success(
                    agentRepository.usageAnalysisByAgent(openid, date, "%" + input + "%",
                        pageable));
        }
        else
        {
            if ("".equalsIgnoreCase(input))
                return this.success(
                    agentRepository.usageAnalysisByAgentByMonth(openid, date, pageable));
            else
                return this.success(
                    agentRepository.usageAnalysisByAgentByMonth(openid, date, "%" + input + "%",
                        pageable));
        }
    }

    @Override
    public Result usageAnalysisByShop(String openid, String date, Integer page, String sort,
                                      String type, String input)
    {
        Pageable pageable = null;
        if (sort.equalsIgnoreCase("desc"))
            pageable = new PageEntity(page, 10, Sort.Direction.DESC, "rate");
        else
            pageable = new PageEntity(page, 10, Sort.Direction.ASC, "rate");

        if (type.equalsIgnoreCase("day"))
        {
            if ("".equalsIgnoreCase(input))
                return this.success(agentRepository.usageAnalysisByShop(openid, date, pageable));
            else
                return this.success(
                    agentRepository.usageAnalysisByShop(openid, date, "%" + input + "%",
                        pageable));
        }
        else
        {
            if ("".equalsIgnoreCase(input))
                return this.success(
                    agentRepository.usageAnalysisByShopByMonth(openid, date, pageable));
            else
                return this.success(
                    agentRepository.usageAnalysisByShopByMonth(openid, date, "%" + input + "%",
                        pageable));
        }
    }

    @Override
    public Result usageAnalysisByDevice(String openid, String date, Integer page, String sort,
                                        String type, String input)
    {
        Pageable pageable = null;
        if (sort.equalsIgnoreCase("desc"))
            pageable = new PageEntity(page, 10, Sort.Direction.DESC, "count");
        else
            pageable = new PageEntity(page, 10, Sort.Direction.ASC, "count");

        if (type.equalsIgnoreCase("day"))
        {
            if ("".equalsIgnoreCase(input))
                return this.success(agentRepository.usageAnalysisByDevice(openid, date, pageable));
            else
                return this.success(
                    agentRepository.usageAnalysisByDevice(openid, date, "%" + input + "%",
                        pageable));
        }
        else
        {

            if ("".equalsIgnoreCase(input))
                return this.success(
                    agentRepository.usageAnalysisByDeviceByMonth(openid, date, pageable));
            else
                return this.success(
                    agentRepository.usageAnalysisByDeviceByMonth(openid, date, "%" + input + "%",
                        pageable));
        }
    }

    @Override
    public Result usageAnalysisByShopInfo(String openid, String date, Integer id, String type)
    {

        Map map = new HashMap();
        if (type.equalsIgnoreCase("day"))
        {
            map.put("info", agentRepository.usageAnalysisByShopInfoInfo(openid, id, date));
            List list = agentRepository.usageAnalysisByShopInfoOrderCount(id, date);
            if (null == list || list.size() == 0)
                map.put("orderCount", this.monthList());
            else
                map.put("orderCount", list);
            map.put("least", agentRepository.usageAnalysisByShopInfoLeast(id, date));
            map.put("weekly", agentRepository.usageAnalysisByShopInfoWeekly(id, date));
            map.put("rate", agentRepository.usageAnalysisByShopInfoRate(openid));
        }
        else
        {
            map.put("info", agentRepository.usageAnalysisByShopInfoInfoByMonth(openid, id, date));
            List list = agentRepository.usageAnalysisByShopInfoOrderCountByMonth(id, date);
            if (null == list || list.size() == 0)
                map.put("orderCount", this.monthList(date.split("-")[1]));
            else
                map.put("orderCount", list);
            map.put("least", agentRepository.usageAnalysisByShopInfoLeastByMonth(id, date));
            map.put("weekly",
                agentRepository.usageAnalysisByShopInfoWeeklyByMonth(id, date + "-01"));
            map.put("rate", agentRepository.usageAnalysisByShopInfoRateByMonth(openid));
        }

        return this.success(map);

    }

    private List<JSONObject> monthList(String str)
    {
        ArrayList<JSONObject> pastDaysList = new ArrayList<>();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("num", 0);
        jsonObject.put("date", str + "-01");
        pastDaysList.add(jsonObject);
        jsonObject = new JSONObject();
        jsonObject.put("num", 0);
        jsonObject.put("date", str + "-05");
        pastDaysList.add(jsonObject);
        jsonObject = new JSONObject();
        jsonObject.put("num", 0);
        jsonObject.put("date", str + "-10");
        pastDaysList.add(jsonObject);
        jsonObject = new JSONObject();
        jsonObject.put("num", 0);
        jsonObject.put("date", str + "-15");
        pastDaysList.add(jsonObject);
        jsonObject = new JSONObject();
        jsonObject.put("num", 0);
        jsonObject.put("date", str + "-20");
        pastDaysList.add(jsonObject);
        jsonObject = new JSONObject();
        jsonObject.put("num", 0);
        jsonObject.put("date", str + "-25");
        pastDaysList.add(jsonObject);
        jsonObject = new JSONObject();
        jsonObject.put("num", 0);
        jsonObject.put("date", str + "-30");
        pastDaysList.add(jsonObject);
        return pastDaysList;
    }

    private List<JSONObject> monthList()
    {
        ArrayList<JSONObject> pastDaysList = new ArrayList<>();
        JSONObject jsonObject = new JSONObject();
        jsonObject = new JSONObject();
        jsonObject.put("num", 0);
        jsonObject.put("date", "00:00");
        pastDaysList.add(jsonObject);
        jsonObject = new JSONObject();
        jsonObject.put("num", 0);
        jsonObject.put("date", "6:00");
        pastDaysList.add(jsonObject);
        jsonObject = new JSONObject();
        jsonObject.put("num", 0);
        jsonObject.put("date", "12:00");
        pastDaysList.add(jsonObject);
        jsonObject = new JSONObject();
        jsonObject.put("num", 0);
        jsonObject.put("date", "18:00");
        pastDaysList.add(jsonObject);
        jsonObject = new JSONObject();
        jsonObject.put("num", 0);
        jsonObject.put("date", "22:00");
        pastDaysList.add(jsonObject);
        return pastDaysList;
    }

    @Override
    public Result deviceOrderInfo(String openid, String sn, Integer page)
    {

        Pageable pageable = new PageEntity(page, 10, Sort.Direction.DESC, "id");
        Map map = new HashMap();
        map.put("info", moneyLogRepository.deviceAmountInfo(openid, sn));
        map.put("data", moneyLogRepository.deviceOrderInfo(openid, sn, pageable));
        return this.success(map);
    }

    @Override
    public Result deleteShop(String openid, Integer oldid, Integer newid)
    {
        // 先判断是否是自己的店铺
        if (!shopRepository.existsByIdAndAgentid(oldid, openid))
            return this.error("名下没有该店铺");

        if (!shopRepository.existsByIdAndAgentid(newid, openid))
            return this.error("名下没有该店铺");
        deviceRepository.updateShop(oldid, newid);
        shopRepository.deleteById(oldid);
        return this.success();
    }

    @Override
    public Result updateEmpName(String openid, Integer id, String name, String telphone)
    {
        Employee employee = employeeRepository.findById(id);
        employee.setName(name);
        employee.setTelphone(telphone);
        employeeRepository.saveAndFlush(employee);
        return this.success();
    }

    @Override
    public Result shopStaff(String openid, Integer id)
    {
        Shop shop = shopRepository.getById(id);
        if (null == shop)
        {
            return this.error("不存在的ID");
        }
        Map map = new HashMap();
        if (null == shop.getOpenid() || "".equalsIgnoreCase(shop.getOpenid()))
            map.put("shop", null);
        else
            map.put("shop", shopRepository.shopStaff(id));

        if (null == shop.getEngId() || "".equalsIgnoreCase(shop.getEngId()))
            map.put("engineer", null);
        else
            map.put("engineer", employeeRepository.shopEng(id));

        if (null == shop.getSalesmanId() || "".equalsIgnoreCase(shop.getSalesmanId()))
            map.put("salesman", null);
        else
            map.put("salesman", employeeRepository.shopSal(id));

        return this.success(map);
    }

    @Override
    public Result submitShopStaff(String openid, Integer id, Integer uid, String type,
                                  Integer commission, String name)
    {
        if (null == commission)
            commission = 0;

        Shop shop = shopRepository.getById(id);

        if (null == uid)
        {
            if (type.equalsIgnoreCase(IdentityKey.shop))
            {
                shop.setOpenid("");
                shop.setCommission(0);
            }
            else if (type.equalsIgnoreCase(IdentityKey.engineer))
            {
                shop.setEngId("");
                shop.setEngCommission(0);
            }
            else
            {
                shop.setSalesmanId("");
                shop.setSalesmanCommission(0);
            }

            shopRepository.save(shop);
            return this.success();
        }

        Identity identity = loginRepository.getById(uid);
        if (null == identity)
            return this.error("不存在的用户ID");

        if (type.equalsIgnoreCase(IdentityKey.shop))
        {
            identity.setName(name);
            if (identity.getType().equalsIgnoreCase(IdentityKey.customer))
            {
                identity.setType(IdentityKey.shop);
                loginRepository.save(identity);
            }
            else if (identity.getType().equalsIgnoreCase(IdentityKey.engineer) ||
                     identity.getType().equalsIgnoreCase(IdentityKey.salesman))
            {
                return this.error("内部员工不得设置为店主");
            }

            shop.setOpenid(identity.getOpenid());
            shop.setCommission(commission);
        }
        else if (type.equalsIgnoreCase(IdentityKey.engineer))
        {
            shop.setEngId(loginRepository.getById(uid).getOpenid());
            shop.setEngCommission(commission);
        }
        else
        {
            shop.setSalesmanId(loginRepository.getById(uid).getOpenid());
            shop.setSalesmanCommission(commission);
        }

        shopRepository.save(shop);
        return this.success();
    }

    @Override
    public Result updateDeviceDesc(String sn, String desc)
    {
        return this.success(deviceRepository.updateDeviceDesc(sn, desc));
    }

    @Override
    public Result agent(Agent agent)
    {
        Identity identity = loginRepository.findByOpenid(agent.getOpenid());
        if (null == identity)
            return this.error(404, "用户不存在");
        if (identity.getType().equalsIgnoreCase(IdentityKey.agent))
            return this.error("用户已经是代理");
        if (identity.getType().equalsIgnoreCase(IdentityKey.engineer) ||
            identity.getType().equalsIgnoreCase(IdentityKey.salesman))
            return this.error("代理员工无法设置为其他身份");
        if (null == agent.getParent() || "".equalsIgnoreCase(agent.getParent()))
        {
            agent.setParent(gm);
        }
        if (!loginRepository.existsByOpenid(agent.getParent()))
            return this.error(404, "不存在的上级代理");
        identity.setType(IdentityKey.agent);
        identity.setLevel(agent.getLevel());
        loginRepository.save(identity);
        agentRepository.save(agent);
        return this.success();
    }

    @Override
    public Result agent(Query query)
    {
        Pageable pageable = new PageEntity(query.getPage(), query.getSize(), Sort.Direction.DESC,
            "id");
        Page<Agent> trees = null;
        if (StringUtils.isNotBlank(query.getType()) && StringUtils.isNotBlank(query.getValue()))
        {
            switch (query.getType())
            {
                case "name":
                    trees = agentRepository.findAllByNameLikeAndLevel(
                        "%" + query.getValue() + "%", 2,
                        pageable);  // 查找所有省代
                    break;
                case "name2":
                    trees = agentRepository.findAllByNameLikeAndLevel(
                        "%" + query.getValue() + "%", 3,
                        pageable);  // 查找所有省代
                    break;
                case "id":
                    trees = agentRepository.findAllById(Integer.valueOf(query.getValue()),
                        pageable);  // 查找所有省代
                    break;
                case "agent":
                    return this.success(agentRepository.findAllByLevel(2));
            }
        }
        else
        {
            trees = agentRepository.findAllByLevel(1, pageable);  // 查找所有省代
        }

        trees.forEach(arr -> {
            List<Agent> list = agentRepository.getAllByParent(arr.getOpenid()); // 省代
            if (null != list && list.size() > 0)
            { // 市代
                list.forEach(temp -> {
                    temp.setChildren(agentRepository.getAllByParent(temp.getOpenid()));
                });
            }
            arr.setChildren(list);
        });
        return this.success(trees);
    }

    @Override
    public Result agentShop(Query query)
    {
        Pageable pageable = new PageEntity(query.getPage(), query.getSize(), Sort.Direction.DESC,
            "id");
        Map map = new HashMap();
        map.put("shop", shopRepository.findAgentShopA(query.getValue(), pageable));
        map.put("employee", employeeRepository.findAllByAgentId(query.getValue()));
        return this.success(map);
    }

    @Override
    public Result agent()
    {
        return this.success(agentRepository.findAllByLevel(2));
    }

    @Override
    public Result allOrders(String value, String start, String end, int page)
    {

        if (StringUtils.isEmpty(value))
            return this.success(orderRepository.allOrders(start, end, page-1));
        return this.success(orderRepository.allOrders("%" + value + "%", start, end, page-1));
    }

    @Override
    public Result allShop(int level, String value, int page)
    {
        Pageable pageable = new PageEntity(page, 10, Sort.Direction.DESC, "id");

        if (StringUtils.isEmpty(value))
        {
            return this.success(shopRepository.allShop(level + 1, pageable));
        }

        return this.success(shopRepository.allShopByValue(level + 1, "%" + value + "%", pageable));
    }

    @Override
    public Result allAgent(int level, String value, int page)
    {
        Pageable pageable = new PageEntity(page, 10, Sort.Direction.DESC, "id");

        if (StringUtils.isEmpty(value))
        {
            return this.success(shopRepository.allAgent(level + 1, pageable));
        }

        return this.success(
            shopRepository.allAgentByValue(level + 1, "%" + value + "%", pageable));
    }

    @Override
    public Result employee(String id)
    {
        return this.success(employeeRepository.findAllByAgentId(id));
    }

    @Override
    public Result withdrawal()
    {
        Map map = new HashMap();
        map.put(IdentityKey.agent, this.agentRepository.withdrawal(IdentityKey.agent));
        map.put("agentAmount", this.agentRepository.withdrawalAmount(IdentityKey.agent));

        map.put(IdentityKey.shop, this.agentRepository.withdrawal(IdentityKey.shop));
        map.put("shopAmount", this.agentRepository.withdrawalAmount(IdentityKey.shop));

        map.put(IdentityKey.customer, this.agentRepository.withdrawal(IdentityKey.customer));
        map.put("customerAmount", this.agentRepository.withdrawalAmount(IdentityKey.customer));

        map.put(IdentityKey.engineer, this.agentRepository.withdrawal(IdentityKey.engineer));
        map.put("engineerAmount", this.agentRepository.withdrawalAmount(IdentityKey.engineer));

        map.put(IdentityKey.salesman, this.agentRepository.withdrawal(IdentityKey.salesman));
        map.put("salesmanAmount", this.agentRepository.withdrawalAmount(IdentityKey.salesman));

        return this.success(map);
    }
}
